'use strict'

const { Controller } = require('egg')

class FeedbackController extends Controller {
  // 添加/删除反馈
  async addOrDelFeedback() {
    const { ctx, service } = this
    // 参数验证
    ctx.validate({
      leaveword_id: { type: 'int', required: true, desc: '留言的id' },
      type: { type: 'int', required: true, range: { in: [1, 2] }, desc: '反馈类型' }
    })
    const { leaveword_id, type } = ctx.request.body
    // 反馈 || 删除反馈
    const result = await service.feedback.addOrDelFeedback({
      leaveword_id,
      user_id: ctx.authUser.id,
      type
    })
    ctx.apiSuccess(result)
  }
  // 查询反馈
  async getFeedback() {
    const { ctx, app } = this
    // 参数验证
    ctx.validate({
      leaveword_id: { type: 'int', required: true, desc: '留言的id' },
      type: { type: 'int', required: true, range: { in: [1, 2] }, desc: '反馈类型' }
    })
    const { leaveword_id, type } = ctx.request.query
    const result = await app.model.Feedback.findOne({
      where: { leaveword_id, type, user_id: ctx.authUser.id }
    })
    ctx.apiSuccess(Boolean(result))
  }
  // 获取举报列表
  async getFeedbackList() {
    const { ctx, app } = this
    // 参数验证
    ctx.validate({
      page: { type: 'int', desc: '页码' },
      pageSize: { type: 'int', desc: '每页条数' },
      type: { type: 'int', range: { in: [1, 2] }, defValue: 2, desc: '反馈类型' },
      order: { type: 'string', range: { in: ['ASC', 'DESC'] }, defValue: 'DESC', desc: '排序方式' }
    })
    const page = ctx.query.page ? parseInt(ctx.query.page) : 1
    const limit = ctx.query.pageSize ? parseInt(ctx.query.pageSize) : 10
    const offset = (page - 1) * limit
    const { type, order } = ctx.query
    const Sequelize = app.Sequelize
    // 查询
    const result = await app.model.Feedback.findAndCountAll({
      where: { type },
      include: [{ model: app.model.Leaveword, attributes: ['id', 'name', 'content'] }],
      attributes: [
        'id',
        'leaveword_id',
        [Sequelize.fn('COUNT', Sequelize.col('leaveword_id')), 'feedback_count']
      ],
      group: ['leaveword_id'],
      order: [[Sequelize.literal('COUNT(leaveword_id)'), order]],
      offset,
      limit
    })

    // 总页数
    result.count = result.count.length
    const totalPage = Math.ceil(result.count / limit)
    result.totalPage = totalPage

    ctx.apiSuccess(result)
  }
  // 删除反馈
  async deleteFeedback() {
    const { ctx, app } = this
    // 参数验证
    ctx.validate({
      ids: { type: 'string', required: true, desc: '留言id' },
      type: { type: 'int', required: true, range: { in: [1, 2] }, desc: '反馈类型' }
    })
    let { ids, type } = ctx.request.body
    // 整理参数
    ids = ids.split(',').map((id) => parseInt(id))
    // 删除
    const result = await app.model.Feedback.destroy({ where: { leaveword_id: ids, type } })
    ctx.apiSuccess(result)
  }
}

module.exports = FeedbackController
